import { defineStore } from "pinia";
import { getDict } from "@/api/dict";
import { useSecureStorage } from "@/util/cryptoData";
const { secureSetItem, secureGetItem,secureRemoveItem } = useSecureStorage();
interface arr {
  [index: string]: any;
}

export const useDictStore = defineStore("dict", {
  state() {
    return {
      dictList: secureGetItem("dictList") || [],
    };
  },
  actions: {
    cleanDictList() {
      this.dictList = [];
      secureRemoveItem("dictList");
    },
    async initDictList() {
      if (this.dictList.length == 0) {
        try {
          await this.getDictList();
        } catch (error) {
          console.log(error);
        }
      }
    },
    getDictList() {
      return new Promise(async (resolve) => {
        try {
          const res = await getDict({
            errorMsg: true,
          });
          if (Array.isArray(res) && res.length > 0) {
            res.forEach((item: any) => {
              item.dict_list = item.dict_list ? JSON.parse(item.dict_list) : [];
            });
            this.dictList = res;
            secureSetItem("dictList", res);
          } else {
            this.dictList = [];
            secureSetItem("dictList", []);
          }
          resolve(true);
        } catch (error) {
          resolve(false);
        }
      });
    },
    //获取全部字典列表
    getAllDict() {
      return this.dictList;
    },
    //获取字典列表
    getDictListByCode(code: string) {
      let dict: arr = [];
      this.dictList.forEach((item: any) => {
        if (item.code == code) {
          dict = item.dict_list.sort((a: any, b: any) => {
            return a.sort - b.sort;
          });
        }
      });
      return dict;
    },
    //获取字典名称
    getDictName(code: string, value: string) {
      let name = "";
      this.dictList.forEach((item: any) => {
        if (item.code == code) {
          item.dict_list.forEach((child: any) => {
            if (child.value == value) {
              name = child.label;
            }
          });
        }
      });
      return name;
    },
    //获取字典值
    getDictValue(code: string, name: string) {
      let value = "";
      this.dictList.forEach((item: any) => {
        if (item.code == code) {
          item.dict_list.forEach((child: any) => {
            if (child.label == name) {
              value = child.value;
            }
          });
        }
      });
      return value;
    },
  },
});
